package com.whzykj.common.wx;

import java.util.Date;
import net.sf.json.JSONObject;

public class WxUtil {
	
/*	
     *//** 正式地址
	public static String appid = "wx92791deb69e1c6eb";
	public static String secret = "1136084bc94726e154d5876a7db7fa7a";
	public static String domain="gth.hbwwcc.com";
	**//*
	
	*//** 测试地址**//*
	public static String appid = "wx7d9d3839bcf7a60b";
	public static String secret = "33e2f83fae30e0b11a1b41d153d68eaf";
	public static String domain="gthtest.hbwwcc.com";
	*/
	
	public static Date tokenTime = null;
	public static Date ticketTime = null;
	public static String token = null;
	public static String ticket = null;

	private static int getDiff(Date begin, Date end) {
		long a = end.getTime();
		long b = begin.getTime();
		int c = (int) ((a - b) / 1000);
		return c;
	}

	
	public static String getOpenid(String code){
		try {
			HttpRequestor http = new HttpRequestor();
			String res = http
			.doGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid="
					+ WxConst.appid
					+ "&secret="
					+ WxConst.secret
					+ "&code="
					+ code
					+ "&grant_type=authorization_code");
			
			String openid =JSONObject.fromObject(res).getString("openid");
			
			return openid;
		}catch (Exception e) {
		}
		return null;
	}
	
	public static String getToken() {
		HttpRequestor http = new HttpRequestor();
		String rs = "";
		try {

			Date now = new Date();

			if (token == null || getDiff(tokenTime, now) > 7000) {
				rs = http
						.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
								+ WxConst.appid + "&secret=" + WxConst.secret);
				tokenTime = now;
				token = JSONObject.fromObject(rs).getString("access_token");

			}
			return token;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 调用微信JS接口的临时票据
	 * 
	 * @param access_token 接口访问凭证
	 * @return
	 */
	public static String getJsApiTicket(String access_token) {
		String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
		String requestUrl = url.replace("ACCESS_TOKEN", access_token);
		HttpRequestor http = new HttpRequestor();
		// 发起GET请求获取凭证
		String rs = "";
		try {

			Date now = new Date();

			if (ticket == null || getDiff(ticketTime, now) > 7000) {
				rs = http.doGet(requestUrl);
				ticketTime = now;
				ticket = JSONObject.fromObject(rs).getString("ticket");
			}
			return ticket;

		} catch (Exception e) {
			rs = "0";
		}
		return null;
	}

	/**
	 * 调用微信用户信息
	 * @param access_token 接口访问凭证
	 * @return
	 */
	public static String getWxUserInfo(String access_token,String openId){
			try {
				HttpRequestor http = new HttpRequestor();
				return http.doGet("https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+openId+"");
			}catch (Exception e) {
			}
			return null;
		}
	
	public static void main(String[] args) {
		String tk = WxUtil.getToken();
		System.out.println(tk);
	}
}
